package singsong;

import java.io.File;

import javax.sound.sampled.AudioSystem;

public class TrackDataBuilder {
	private RegularAudioInputStream audioInputStream;
	
	private TrackData data;
	
	public TrackDataBuilder(String filename, float samplingRate, float startTime) {
		audioInputStream = new RegularAudioInputStream(filename);
		data = new TrackData(samplingRate);
		data.addSilence(startTime);
	}
	
	public TrackData build() {
		FrequencyAnalyzer frequencyAnalyzer = new FrequencyAnalyzer((int) audioInputStream.getSamplesPerSecond());
		VolumeAnalyzer volumeAnalyzer = new VolumeAnalyzer();
		float sampleTime = 0;
		while (!audioInputStream.isEndOfStream()) {
			float sample = audioInputStream.nextSample();
			volumeAnalyzer.addSample(sample);
			frequencyAnalyzer.addSample(sample);
			sampleTime += audioInputStream.getSampleDuration();
			if (sampleTime > data.getSampleDuration()) {
				sampleTime -= data.getSampleDuration();
				data.addSample(frequencyAnalyzer.getFrequency(), volumeAnalyzer.getVolume());
			}
		}
		backfillFrequencyData();
		return data;
	}

	private void backfillFrequencyData() {
		float firstFrequency = 0;
		for (TrackData.Sample sample : data.getSamples()) {
			if (sample.getFrequency() != 0) {
				firstFrequency = sample.getFrequency();
				break;
			}
		}
		if (firstFrequency != 0) {
			for (TrackData.Sample sample : data.getSamples()) {
				if (sample.getFrequency() == 0) {
					sample.setFrequency(firstFrequency);
				}
			}
		}
	}
}
